package com.lf.web.service.system.webnode;

import com.lf.data.Cluster;
import com.lf.data.ClusterUtil;
import com.lf.web.service.ResponseCode;
import com.lf.web.service.ResponseInfo;
import com.lf.web.service.ServiceSupport;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class WebNodeAddService extends ServiceSupport {

    private static final Logger LOGGER = Logger.getLogger(WebNodeAddService.class);
    private WebNodeDAO webNodeDAO;
    private List<Cluster> channels = null;

    public void setWebNodeDAO(WebNodeDAO webNodeDAO) {
        this.webNodeDAO = webNodeDAO;
    }

    public String execute() {
        String type = form.getString("type");
        if ("save".equals(type)) {
            return save();
        } else {
            channels = webNodeDAO.find(null, null, null);
            context.put("parentid", form.getString("parentid"));
            context.put("channels", channels);
            context.put("check", ClusterUtil.getCheck(Cluster.class));
            return "add";
        }
    }

    private String save() {
        WebNode webNode = new WebNode();
        boolean result = form.getCluster(webNode);
        LOGGER.debug("添加频道：" + webNode);
        if (result) {
            ResponseInfo rj = new ResponseInfo();
            String parentid = webNode.getString(WebNode.PARENT_ID);
            List parent;
            if (parentid.equals("")) {
                parent = new ArrayList();
            } else {
                Cluster cluster = webNodeDAO.findById(parentid);
                if (cluster.isEmpty()) {
                    rj.setCode(ResponseCode.EXIST_NOT);
                    out(rj);
                    return NONE;
                } else {
                    parent = cluster.getList(WebNode.PARENT);
                }
            }
            String id = webNode.setId();
            parent.add(webNode.get(WebNode.ID));
            webNode.put(WebNode.PARENT, parent);
            webNode.put(WebNode.DEEP, parent.size());
            webNode.put(WebNode.CREATED, new Date());
            webNodeDAO.insert(webNode);
            rj.setCode(ResponseCode.FINISH);
            rj.put("id", id);
            out(rj);
        } else {
            error(404);
            LOGGER.error("非法添加频道：" + webNode);
        }
        return NONE;
    }

}
